var form = layui.form, laydate = layui.laydate, annexData = [], upload = layui.upload, table = layui.table, $ = layui.jquery,annexList = [],data2=[]
    id = getQueryVariable("id");
layui.use(['tableEdit'], function () {

    (function ($) {
        //默认参数
        var defaluts = {
            searchName: '.ySearchSelect'
        };

        $.fn.extend({
            "ySearchSelect": function (options) {
                defaluts.searchName = options;
                var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
                return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                    init(opts);
                });

            }
        });
        $(document).ready(function () {
            //加载签约公司
            $.ajax({
                url: 'billDeclare/selectAllcompanyAndpeople',
                type: 'GET',
                async: false, // 同步
                success: function (date) {
                    var map=date.data
                    var company=[]
                    $.each(map, function (key, value) {
                        if(key=="companyName"){
                            company=value
                        }
                    });
                    for(let i in company){
                        $("#signingcompany").append("<option value='"+company[i].code+"'>"+company[i].name+"</option>")
                    }
                    form.render();
                }
            });
            if(id==""){
                id=-1;
            }
            firstGet()
            if(id!=-1){//修改报关进行加载
                $.ajax({
                    url: 'billDeclare/selectBillById?billId='+id,
                    type: 'GET',
                    success: function (date) {
                        billInfo=date.data
                        showBill(billInfo)
                    }
                });
                $.ajax({
                    url: 'billDeclare/selectProductAndPartsById?billId='+id,
                    type: 'GET',
                    success: function (date) {
                        billProducts=date.data
                        table.reload('storageproductstableid',{
                            data:billProducts
                        })
                    }
                });
                //加载附件
                $.ajax({
                    url: 'billDeclare/selectBillFile?type=1&parentId='+id,
                    type: 'GET',
                    success: function (date) {
                        annexList=date.data;
                       table.reload('attachmenttableid', {data:date.data});;
                    }
                });
            }

        })
        function showBill(first){
            $("input[name='invoicenumber']").val(first.invoiceNo);
            $("input[name='contact']").val(first.linker);
            $("input[name='shdate']").val(first.shippingDate);
            $("input[name='exchangerate']").val(first.usdRate);
            $("input[name='rmbexchangerate']").val(first.rmbRate);
            $("input[name='modetransportation']").val(first.transMode);
            $("input[name='invoicetotalamount']").val(first.invoicemoney);
            $("input[name='mdate']").val(first.createTime);
            $("input[name='salescontractno']").val(first.contractNo);
            $("input[name='customercontractno']").val(first.custContractNo);
            $("input[name='actualdischargedateatd']").val(first.atdDate);
            $("input[name='wldate']").val(first.inStockDate);
            $("input[name='salesman']").val(first.salesmanName);
            $("input[name='customername']").val(first.custName);
            $("input[name='currency']").val(first.moneyName);
            $("input[name='businessmodel']").val(first.businessMode);
            $("input[name='theoperator']").val(first.operator);
            $("input[name='customsdeclaration']").val(first.billCustmsDeclareNo);
            $("input[name='cdate']").val(first.declarationDate);
            $("input[name='esetddate']").val(first.etdDate);
            $("input[name='endesetddate']").val(first.etaDate);
            $("input[name='theoperator']").val(first.opName);
            $("#place").find("option[value='"+first.startplace+"']").attr("selected",true);
            $("#destination").find("option[value='"+first.endplace+"']").attr("selected",true);
            $("#settlementway").find("option[value='"+first.settleMode+"']").attr("selected",true);
            $("#priceterms").find("option[value='"+first.priceTerm+"']").attr("selected",true);
            $("#bank").find("option[value='"+first.bankName+"']").attr("selected",true);
            $("#signingcompany").find("option[value='"+first.companyName+"']").attr("selected",true);
            // .val(first.companyName);
            $("#signingcompanyCode").val(first.companyCode);
            $("#custCode").val(first.custCode);
            $("#salesmanCode").val(first.salesmanCode);
            $("#opCode").val(first.opCode);
            $("#coefficient").val(first.coefficient);
            var s="否"
            if(first.whetherCreditGuarantee==1){
                s="是(采购抬头：上海沣奇)"
            }else if (first.whetherCreditGuarantee==2){
                s="是(采购抬头：上海源铢)"
            }
            $("#whetherCreditGuarantee").val(s);
            $("#creditGuaranteeAmount").val(first.creditGuaranteeAmount);
            form.render();
        }
        //初始化插件
        function init(o) {
            $(document).click(function () {
                var thin = this;

                $(".ySearchSelect table").hide();
                $(".ySearchSelect .input-text").hide();
                $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
                $(".ySearchSelect i.layui-edge").removeClass("select");

            });


            $(o.searchName + " .layui-input").click(function (event) {
                //阻止document点击事件
                event.stopPropagation();
                if ($(this).siblings(".input-text").length <= 0) {
                    var str = '<div class="input-text">' +
                        '<input type="text" name="" placeholder="输入关键字" class="layui-input">' +
                        '</div>';
                    $(o.searchName).append(str);
                }
                if ($(this).siblings("table").css("display") == "none") {
                    var ids = $(o.searchName).attr("data-id");
                    table.render({
                        elem: '#productcodeselect_' + ids,
                        id: 'productcodeselecttableid_' + ids,
                        data: data3,
                        cols: [[
                            {field: 'productcode', width: 220, title: '产品编码'},
                            {field: 'specificationcoding', width: 120, title: '规格编码'},
                            {field: 'chinesename', width: 120, title: '中文名称'},
                            {field: 'englishnames', width: 120, title: '英文名称'},
                            {field: 'productcatalog', width: 120, title: '产品目录'}
                        ]],
                        height: 200
                    });
                    table.on('row(productcodeselecttable_' + ids + ')', function (obj) {
                        var data = obj.data;
                        var tabledata = table.cache["storageproductstableid"];
                        $.each(tabledata, function (index, value) {
                            if (value.id == ids) {
                                tabledata[index]["productcode"] = data.productcode;
                            }
                        });
                        table.reload('storageproductstableid', {});
                    });
                    $(this).siblings("i").addClass("select");
                    $(this).siblings("table").show();
                    $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                    $(this).siblings(".input-text").show();
                } else {
                    $(this).siblings("i").removeClass("select");
                    $(this).siblings("table").hide();
                    $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                    $(this).siblings(".input-text").hide();
                }
                $(o.searchName + " .input-text input").focus();
                $(o.searchName + " .input-text").width(605);

                //键盘监听事件
                $(o.searchName + " .input-text input").keyup(function (event) {
                    if (event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 13) {
                        ySearchSelectMate($(this).val(), o.searchName);
                    }
                });
            });
        }

        //匹配搜索，不匹配则隐藏。
        function ySearchSelectMate(value, name) {
            value = $.trim(value.toString()); // 去掉两头空格
            var ids = $(name).attr("data-id");
            //模糊查询表格并刷新
            table.reload('productcodeselecttableid_' + ids, {
                where: {
                    productcode: value
                }
            });
        }
    })(window.jQuery);


    function firstGet() {
        getPriceTerm()
        getsettleMode()
        getstartplace()
        getendplace()
        getbank()
        getCoefficient();
        form.render();
    }
    function  getCoefficient() {
        var  coefficient= getdictionary(6,60)
        $("#coefficient").val(parseFloat(coefficient[0].name))
    }
    function  getPriceTerm(){
        var  PriceTerm= getdictionary(5,16)
        for(let i in PriceTerm){
            $("#priceterms").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
        }
    }
    function  getsettleMode(){
        var  PriceTerm= getdictionary(5,18)
        for(let i in PriceTerm){
            $("#settlementway").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
        }
    }
    function  getstartplace(){
        var  PriceTerm= getdictionary(6,31)
        for(let i in PriceTerm){
            $("#place").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
        }
    }
    function   getendplace(){
        var  PriceTerm= getdictionary(6,29)
        for(let i in PriceTerm){
            $("#destination").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
        }
    }
    function   getbank(){
        var  PriceTerm= getdictionary(6,32)
        for(let i in PriceTerm){
            $("#bank").append("  <option value='"+PriceTerm[i].name+"'>"+PriceTerm[i].name+"</option>")
        }
    }



    var data0 = [];
    var data1 = [];
    var data2 = [];
    var data3 = [];

    lay('.starttime').each(function () {
        laydate.render({
            elem: this,
            type: 'date',
            // showBottom: false,
            done: function (value, date, endDate) {
                if (this.elem[0].id == "actualdischargedateatd" || this.elem[0].id == "wldate" || this.elem[0].id == "esetddate" || this.elem[0].id == "endesetddate") {
                    if (value != "") {
                        $("." + this.elem[0].id + "text").css("background", "#fff");
                    } else {
                        $("." + this.elem[0].id + "text").css("background", "red");
                    }
                }

            }
        });
    });
//表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "invoicenumber": "进入修改",
        })
    }
//监听提交
    form.on('submit(form-element)', function (data) {
        //防止重复提交问题
        preventDuplicateSubmissions();
        var indexsl = 0;
        var storageproductsdata = table.cache["storageproductstableid"];
        var product=new Array();
        for(let i in storageproductsdata){
            if(storageproductsdata[i]!=[]&&storageproductsdata[i]!=null&&storageproductsdata[i]!=""){
                product.push(storageproductsdata[i])
            }
        }
        var costtabledata = table.cache["costtableid"];
        $.each(storageproductsdata, function (index, value) {
            // if (typeof (storageproductsdata[index]["goodsCode"]) == "undefined" || storageproductsdata[index]["goodsCode"] == "") {
            //     layer.msg("产品表第" + (index + 1) + "条产品编码不能为空");
            //     indexsl++;
            //     return false;
            // } else if (typeof (storageproductsdata[index]["declarePrice"]) == "undefined" || storageproductsdata[index]["declarePrice"] == "") {
            //     layer.msg("产品表第" + (index + 1) + "条单价不能为空");
            //     indexsl++;
            //     return false;
            // }
            return false;
        });

        if (indexsl == 0) {
            //提交form表单，返回报关表单id值，再提交产品表
            var bill=getBillFrom()
            var billid=""
            $.ajax({
                url: 'billDeclare/addBillInfo?id='+id,
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                async: false, // 同步
                data: JSON.stringify(bill),
                success: function (date) {
                    billid=date.data
                }
            });
            $.ajax({
                url: 'billDeclare/addBillProductInfo?billid='+billid+"&id="+id,
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                async: false, // 同步
                data: JSON.stringify(product),
                success: function (date) {
                    if(date.data!="wrong"){
                    }else{
                        layer.msg("保存失败", {icon: 6});
                    }
                }
            });


        }
        //提交附件
        //获取头部表单数据
        let req = data.field;
            //获取附件数据
            let annexReqs = table.cache["attachmenttableid"];
            let datas = JSON.stringify(annexReqs);
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:datas,
                url:"billDeclare/add?id="+billid+"&type="+id,
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            parent.detab("views/jsp/ExportBusiness/tpl/newupcustomsdeclaration.jsp");
                            parent.intab("views/jsp/ExportBusiness/customsdeclaration.jsp", "报关")
                            parent.detab("views/jsp/ExportBusiness/tpl/newupcustomsdeclaration.jsp" + (id == '' ? '' : '?id=' + id));
                            //保存成功则刷新提交过来的界面 并关闭此页面
                        }, 1000);
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    return false;
                }
            });
            //刷新父页面
        setTimeout(function () {
            //保存成功则刷新提交过来的界面 并关闭此页面
            parent.detab("views/jsp/ExportBusiness/customsdeclaration.jsp");
            parent.intab("views/jsp/ExportBusiness/customsdeclaration.jsp","报关")
        },1000);
        return false;
    });
        return false;
    });

    function getBillFrom(){
        var s=0;
        if($("#whetherCreditGuarantee").val()=="是(采购抬头：上海沣奇)"){
            s=1
        }else if($("#whetherCreditGuarantee").val()=="是(采购抬头：上海源铢)") {
            s=2
        }
        var bill={
            "carryId":$("#carryIds").val(),
            "linker":$("input[name='contact']").val(),
            "salesmanName":$("input[name='salesman']").val(),
            "invoiceNo":$("input[name='invoicenumber']").val(),
            "shippingDate":$("input[name='shdate']").val(),
            "custName": $("input[name='customername']").val(),
            "usdRate":$("input[name='exchangerate']").val(),
            "rmbRate":$("input[name='rmbexchangerate']").val(),
            "transMode":$("input[name='modetransportation']").val(),
            "invoicemoney": $("input[name='invoicetotalamount']").val(),
            "createTime":$("input[name='mdate']").val(),
            "contractNo":$("input[name='salescontractno']").val(),
            "custContractNo":$("input[name='customercontractno']").val(),
            "atdDate":$("input[name='actualdischargedateatd']").val(),
            "inStockDate":$("input[name='wldate']").val(),
            "salesmanName":$("input[name='salesman']").val(),
            "moneyName": $("input[name='currency']").val(),
            "businessMode": $("input[name='businessmodel']").val(),
            "opName": $("input[name='theoperator']").val(),
            "startplace":$("#place").val(),
            "endplace": $("#destination").val(),
            "settleMode":$("#settlementway").val(),
            "priceTerm":$("#priceterms").val(),
            "bankName":$("#bank").val(),
            "billCustmsDeclareNo":$("input[name='customsdeclaration']").val(),
            "declarationDate":$("input[name='cdate']").val(),
            "etdDate":$("#esetddate").val(),
            "etaDate":$("#endesetddate").val(),
            "companyName":$("#signingcompany").find("option:selected").text(),
            "companyCode":$("#signingcompany").val(),
            "custCode":$("#custCode").val(),
            "opCode":$("#opCode").val(),
            "salesmanCode":$("#salesmanCode").val(),
            "customerLevelName":$("#customerLevelName").val(),
            "customerLevelCode":$("#customerLevelCode").val(),
            "coefficient":$("#coefficient").val(),
            "whetherCreditGuarantee":s,
            "creditGuaranteeAmount":$("#creditGuaranteeAmount").val()
        }
        return bill;

    }
    let data4=[];
    var hs=[];

    let isContainsRole=false;
    getIsContainsRole();

//--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data:data4,
        toolbar: '#storageproductstoolbar',
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'stockNo', width: 120, title: '采购单号', edit: 'text'},
            {field: 'goodsCode', width: 220, title: '产品编码'},
            {field: 'specCode', width: 120, title: '规格编码'},
            {field: 'specNo', width: 120, title: '规格说明'},
            {field: 'producttype', width: 120, title: '产品类型', templet: function(element){
                    var     producttype="";
                    if(element.producttype==1){ producttype="成品";}else{producttype="配件";}
                    return producttype;
                }},
            //暂无
            // {field: 'customersarticlenumber', width: 120, title: '客户货号', edit: 'text'},
            {field: 'goodsCname', width: 120, title: '中文名称'},
            {field: 'goodsEname', width: 120, title: '英文名称'},
            {field: 'hsCode', title: '海关编码', width: 240, templet:'#hsCodeSelect'},
            {field: 'billGoodsCname', title: '报关中文品名', width: 140, edit: 'text'},
            {field: 'billGoodsEname', title: '报关英文品名', width: 140, edit: 'text'},
            {field: 'hsMemo', width: 120, title: '报关要素', edit: 'text'},
            {field: 'unit', width: 120, title: '报关单位', edit: 'text'},
            {field: 'addRate', width: 120, title: '增值税率', edit: 'text'},
            {field: 'backRate', width: 120, title: '退税率', edit: 'text'},
            {field: 'goodsCdesc', width: 120, title: '中文描述'},
            {field: 'goodsEdesc', width: 120, title: '英文描述'},
            {field: 'goodsNum', width: 120, title: '产品数量'},
            //数量需要进行调整
            {field: 'mastAmount', width: 120, title: '剩余数量', templet: function(element){
                    var  ftotalprice=element.lastAmount;
                    if(id!=-1){
                        $.ajax({
                            url: 'billDeclare/selectLastAmontById?proid='+element.declareProductId,
                            type: 'GET',
                            async: false, // 同步
                            success: function (date) {
                                ftotalprice=date.data+element.lastAmount;
                            }
                        });
                    }
                    return ftotalprice;
                }},
            {field: 'lastAmount', width: 120, title: '报关数量', edit: 'text'},
            {field: 'goodsUnit', width: 120, title: '单位', edit: 'text'},
            {field: 'funitprice', width: 80, title: '单价',hide:!isContainsRole},
            //进行计算 金额小计=单价*数量
            {field: 'ftotalprice', width: 120, title: '金额小计',hide:!isContainsRole},
            {field: 'color', width: 120, title: '颜色', edit: 'text'},
            {field: 'goodsGross', width: 120, title: '毛重', edit: 'text'},
            {field: 'totalGross', width: 120, title: '毛重小计'},
            {field: 'netweight', width: 120, title: '净重', edit: 'text'},
            {field: 'totalnet', width: 120, title: '净重小计'},
            {field: 'bulk', width: 120, title: '体积', edit: 'text'},
            {field: 'totalBulk', width: 120, title: '体积小计'},
            //托数=数量/每托量
            {field: 'trayNumber', width: 120, title: '每托量', edit: 'text'},
            {field: 'totalTray', width: 120, title: '托数'},
            {field: 'perpiecesNum', width: 120, title: '每件数量', edit: 'text'},
            {field: 'piecesNum', width: 120, title: '件数'},
            //暂无
            // {field: 'paymentpaymentdays', width: 120, title: '付款账期', edit: 'text'},
            {field: 'costUnitPrice', width: 120, title: '成本单价', edit: 'text'},
            //成本小计=数量*成本单价
            {field: 'costSubtotal', width: 120, title: '成本小计', edit: 'text'},
            {field: 'outerLenght', title: '外包装长', width: 120, edit: 'text'},
            {field: 'outerWidth', title: '外包装宽', width: 120, edit: 'text'},
            {field: 'outerHeight', title: '外包装高', width: 120, edit: 'text'},
            //进行计算 外包装尺寸=外包装长*外包装宽*外包装高
            {field: 'ccc', title: '外包装尺寸', width: 120, edit: 'text', templet: function(element){
                    var leng=0;var width=0;var heigh=0;
                    if(element.outerLenght!=null){
                        leng= element.outerLenght
                    }
                    if(element.outerWidth!=null){
                        width=element.outerWidth
                    }
                    if(element.outerHeight!=null){
                        heigh=element.outerHeight
                    }
                    return leng+"*"+width+"*"+heigh;
                }},
            {field: 'supplyerName', width: 120, title: '供应商', edit: 'text'},
            {field: 'clientContractNo', width: 120, title: '客户合同号', edit: 'text'},
            {field: 'saleContractNo', width: 120, title: '外销合同号', edit: 'text'},
            {field: 'stockPrice', width: 120, title: '采购单价', edit: 'text'},
            {field: 'declarePrice', title: '报关单价', width: 120,  templet: function(element){
                  return  toDecimal4( ( (element.stockPrice*element.lastAmount)/1.13/parseFloat($("#coefficient").val()))/element.lastAmount)
            }},
            //报关金额小计=报关单价*数量
            {field: 'totalPrice', title: '报关金小计', width: 120,  templet: function(element){
                    return  toDecimal4( ( (element.stockPrice*element.lastAmount)/1.13/parseFloat($("#coefficient").val())))
                }},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}]],
        // page: true,
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')

            hs=getdictionary(3,8)
            var html=""
            for(let i in hs){
                html+="<option value='"+hs[i].code+hs[i].name+"' >"+hs[i].code+hs[i].name+"</option>"
            }
            $(".hsCodeSelect").append(html)
            for (var i = 0; i < res.data.length; i++) {
                var classs = ".y_" + res.data[i].id;
                $(classs).ySearchSelect(classs);
                $('.hsCodeSelect:eq('+i+') option[value="'+res.data[i].hsCode+'"]').prop("selected",true);
            }
            form.render('select');
        }
    });
    function getdictionary(dl,xl) {
        var obj=[];
        $.ajax({
            type : 'POST',
            //  url : 'resource/getTree',
            data: {"type":dl,"lx":xl},
            url:'dictionary2/getValues',
            dataType:"json",
            // contentType: 'application/json',
            async:false,
            success : function (da) {
                if(da.status==200 ){
                    obj=da.data;
                    hs=obj;
                }
            },
            error: function(data) {
                // layer.msg("获取失败!");
            }
        });
        return obj;
    }


    //监听海关编码下拉框
    form.on("select(hsCodeSelect_filter)", function(data){

        var hs=getdictionary(3,8);
        var elem = data.othis.parents("tr");
        var hsC=data.value;
        var dataindex = elem.attr("data-index");
        var tabledata = table.cache["storageproductstableid"];
        var inde='';
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["hsCode"] = data.value;
                for(let i in hs){
                    var codeName=hs[i].code+hs[i].name
                    if(data.value==codeName){
                        tabledata[index]["billGoodsCname"] = hs[i].name;
                        tabledata[index]["billGoodsEname"] = hs[i].englishname;
                        tabledata[index]["hsMemo"] = hs[i].declarationElements;
                        tabledata[index]["unit"] = hs[i].unitOfQuantity;
                        tabledata[index]["addRate"] = hs[i].vatRate;
                        tabledata[index]["backRate"] = hs[i].taxRate;
                        // $('.hsCodeSelect:eq('+index+') option[value="'+hsC+'"]').prop("selected",true);
                    }
                }
            }
        });

        table.reload('storageproductstableid', {
            data:tabledata
        });
        form.render();
    });

    form.on("select(grossweightselect_filter)", function (data) {
        var elem = data.othis.parents("tr");
        var dataindex = elem.attr("data-index");
        var tabledata = table.cache["storageproductstableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["grossweight"] = data.value;
            }
        });
    });
    form.on("select(customscodeselect_filter)", function (data) {
        var elem = data.othis.parents("tr");
        var dataindex = elem.attr("data-index");
        var tabledata = table.cache["storageproductstableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["customscode"] = data.value;
            }
        });
    });
    form.on("select(unitselect_filter)", function (data) {
        var elem = data.othis.parents("tr");
        var dataindex = elem.attr("data-index");
        var tabledata = table.cache["storageproductstableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["unit"] = data.value;
            }
        });
    });

    table.on('edit(storageproductstable)', function (obj) {//表格内进行修改
         
        var declare=obj.data //得到当前行数据
        var tabledata = table.cache["storageproductstableid"];
        if(obj.field=="declarePrice"){//当前编辑的字段名
            var newInt=parseInt(obj.value)
            declare.totalPrice=newInt*declare.lastAmount
            obj.update(declare) //修改当前行数据
        }
        var old = $(this).prev().text();//旧值
        if(obj.field=="lastAmount"){
            var newInt=parseFloat(obj.value)
            var oldInt=parseFloat(old)
            if(id!=-1){
                $.ajax({
                    url: 'billDeclare/selectLastAmontById?proid='+declare.declareProductId,
                    type: 'GET',
                    async: false, // 同步
                    success: function (date) {
                        oldInt=date.data+declare.lastAmount;
                    }
                });
            }
            if(newInt>oldInt){
                // layer.msg('数量超过可报关数量，请重新输入');
                // $(this).val(old);
                // return;
            }else if(newInt<0){
                layer.msg('数量不能为负，请重新输入');
                $(this).val(old);
                return;
            }else{//修改成功后，进行全段修改
                declare.costSubtotal=toDecimal(newInt*declare.costUnitPrice)//成本小计
                declare.ftotalprice=toDecimal(newInt*declare.funitprice)//金额小计
                declare.totalTray=toDecimal(newInt/declare.trayNumber)//托数
                var newNum= toDecimal(newInt/declare.perpiecesNum)
                declare.piecesNum=newNum//件数
                declare.totalGross=toDecimal(newNum*declare.goodsGross)//毛重小计
                declare.totalnet=toDecimal(newNum*declare.netweight)//净重小计
                declare.totalBulk=toDecimal(newNum*declare.bulk)//体积小计
                var allPic=newInt*declare.stockPrice //采购总额
                var coefficient=$("#coefficient").val()
                var totalPrice=toDecimal4(allPic/1.13/parseFloat(coefficient)) //报关金额小计
                declare.totalPrice=totalPrice;
                declare.declarePrice=toDecimal4(declare.totalPrice/newInt);
                //
                obj.update(declare) //修改当前行数据
            }
        }
        if(obj.field=="stockPrice"){//修改采购单价
            var stockPrice=parseFloat(obj.value)
            var allPic=declare.lastAmount*stockPrice //采购总额
            var coefficient=$("#coefficient").val()
            var totalPrice=toDecimal4(allPic/1.13/parseFloat(coefficient)) //报关金额小计
            declare.totalPrice=totalPrice;
            declare.declarePrice=toDecimal4(totalPrice/declare.lastAmount);
            obj.update(declare) //修改当前行数据
        }
        if(obj.field=="goodsGross"){
            var newInt=parseFloat(obj.value)
            declare.totalGross=toDecimal(newInt*declare.piecesNum)//毛重小计
            obj.update(declare) //修改当前行数据
        }
        if(obj.field=="netweight"){
            var newInt=parseFloat(obj.value)
            declare.totalnet=toDecimal(newInt*declare.piecesNum)//净重小计
            obj.update(declare) //修改当前行数据
        }
        if(obj.field=="bulk"){
            var newInt=parseFloat(obj.value)
            declare.totalBulk=toDecimal(newInt*declare.piecesNum)//体积小计
            obj.update(declare) //修改当前行数据
        }
        if(obj.field=="trayNumber"){
            var newInt=parseFloat(obj.value)
            declare.totalTray=toDecimal(declare.lastAmount/newInt)//托数
            obj.update(declare) //修改当前行数据
        }
        if(obj.field=="perpiecesNum"){//修改每件件数
            var newInt=parseFloat(obj.value)
            var newNum= toDecimal(declare.lastAmount/newInt)//件数
            declare.piecesNum=newNum
            declare.totalGross=toDecimal(newNum*declare.goodsGross)//毛重小计
            declare.totalnet=toDecimal(newNum*declare.netweight)//净重小计
            declare.totalBulk=toDecimal(newNum*declare.bulk)//体积小计
            obj.update(declare) //修改当前行数据
        }
        if(obj.field=="costUnitPrice"){//修改成本
            var newInt=parseFloat(obj.value)
            declare.costSubtotal=toDecimal(declare.lastAmount*newInt)
            obj.update(declare) //修改当前行数据
        }
        if(obj.field=="funitprice"){//修改金额小计
            var newInt=parseFloat(obj.value)
            declare.ftotalprice=toDecimal(declare.lastAmount*newInt)
            obj.update(declare) //修改当前行数据
        }
        var html=""
        for(let i in hs){
            html+="<option value='"+hs[i].code+hs[i].name+"' >"+hs[i].code+hs[i].name+"</option>"
        }
        $(".hsCodeSelect").append(html)
        for (var i = 0; i < tabledata.length; i++) {
            $('.hsCodeSelect:eq('+i+') option[value="'+tabledata[i].hsCode+'"]').prop("selected",true);
        }
        form.render('select');
        //判断数据类型 ,,,,,,,
        if ((obj.field == "number" || obj.field == "unitprice" || obj.field == "amountsubtotal" || obj.field == "volume" || obj.field == "joenumber" || obj.field == "quantityeachhold" || obj.field == "costunitprice" || obj.field == "costsubtotal" || obj.field == "finishedproductcost" || obj.field == "sparepartscost" || obj.field == "customscode" || obj.field == "cuunitprice" || obj.field == "cugoldsubtotal") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }

    });
    table.on('tool(storageproductstable)', function (obj) {
        if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                //需要删除的ID：data.id
                obj.del();
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });
    function toDecimal(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return;
        }
        f = Math.round(x*100)/100;
        return f;
    }
    function toDecimal4(x){
     return  x.toFixed(4)
    }
    table.on('toolbar(storageproductstable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'importshipmentdetails':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/importshipmentdetails.jsp',
                    end:function () {
                        form.render();
                    }
                });
                break;
            case 'new':
                var oldData = table.cache["storageproductstableid"];
                var data1 = {
                    "id": oldData.length + 1,
                    warehousename: "",
                    number: "",
                    unitprice: "",
                    amountsubtotal: "",
                    costprice: "",
                    costsubtotal: "",
                    productcode: ""
                };
                oldData.push(data1);
                table.reload('storageproductstableid', {data: oldData});
                break;
            case 'del':
                var data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', function (index) {
                        var cbList = table.cache["storageproductstableid"];
                        //要在cblist中删除delist数据
                        var showList=[];
                        for(let i in cbList){
                            var old=cbList[i]//用来比较，如果都不等于该值，则用于显示
                            let eq=false;
                            for(let j in delList){
                                var iseq= isObjEqual(old,delList[j])
                                if(iseq){
                                    eq=true
                                }
                            }
                            if(eq==false){
                                showList.push(old)
                            }
                        }
                        table.reload("storageproductstableid", {
                            data: showList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        }
        ;
    });
    function isObjEqual(o1,o2){//相等返回true  01 proid=1 partid=null  02 praid=1 partid=1
        var equal=false;
        if(o1.carryPartsId==null&&o2.carryPartsId==null){
            if(o1.carryProductsId==o2.carryProductsId){
                equal=true;
            }
        }else{
            if(o1.carryPartsId==o2.carryPartsId&&o1.carryProductsId==o2.carryProductsId){
                equal=true;
            }
        }
        return equal;
    }

//---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'billDeclare/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?', function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }
    });

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: data2
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });


    function deleteProducts(){
        var checkStatus = table.checkStatus('storageproductstableid'); //idTest 即为基础参数 id 对应的值
        checkStatus.data//选中行数据
        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        layer.close(index);
    }

    //验证单号是否唯一
    function checkBillNo() {
        var invoicenumber=$("input[name='invoicenumber']").val()
        $.ajax({
            url: 'billDeclare/checkBillNo?invoicenumber='+invoicenumber+"&id="+id,
            type: 'GET',
            async: false, // 同步
            success: function (date) {
              if(date.data=="wrong"){
                  $("input[name='invoicenumber']").val("")
                  layer.msg("报关发票号已存在,请重新输入")
              }

            }
        });
    }


function getIsContainsRole(){
    $.ajax({
        url: 'billDeclare/isContainsRole',
        async: false, // 同步
        success: function (data) {
            if (data.status==200){
                isContainsRole=data.data;
            }
        }
    });
}
